package com.chinackts.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.CountDownLatch;

/**
 * @author Lianhong
 * @since 2021/10/28
 * 电子口岸 webSocket 客户端
 */
public class EPortWebSocketClient extends WebSocketClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(EPortWebSocketClient.class);

    public EPortWebSocketClient() throws URISyntaxException {
        super(new URI("ws://127.0.0.1:61232"));
    }

    private final Object lock = new Object();
    private String result = null;

    private CountDownLatch downLatch = null;

    public JSONObject sendText(String text) {
        synchronized (lock) {
            downLatch = new CountDownLatch(1);
            send(text);
            try {
                downLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return JSON.parseObject(result);
        }
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        LOGGER.info("[websocket connection success]");
    }

    @Override
    public void onMessage(String s) {
        LOGGER.info("[websocket receive message: {}]", s);
        result = s;
        if (downLatch != null && !"open".equals(JSON.parseObject(s).getString("_method"))) {
            downLatch.countDown();
        }
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        LOGGER.info("[websocket connection close]");
    }

    @Override
    public void onError(Exception e) {
        LOGGER.info("[websocket connection error: {}]", e.getMessage());
    }
}
